package org.twdata.pipeline;

import org.apache.commons.pool.*;

import org.apache.commons.pool.impl.*;

/**  Manages instances of pipeline stages by pooling them */
public class PooledStageManager implements StageManager {

    private KeyedPoolableObjectFactory factory;
    private KeyedObjectPool pool;
    private int poolMax = 100;
    private int poolInit = 10;


    /**
     *  Sets the factory for creating new stages
     *
     *@param  factory  The factory
     */
    public void setKeyedPoolableObjectFactory(KeyedPoolableObjectFactory factory) {
        this.factory = factory;
    }


    /**
     *  Sets the max size of the pool
     *
     *@param  max  The new max size
     */
    public void setPoolMax(int max) {
        this.poolMax = max;
    }


    /**
     *  Sets the initial size of the pool
     *
     *@param  initial  The new initial pool size
     */
    public void setPoolInitial(int initial) {
        this.poolInit = initial;
    }


    /**  Initializes the pool */
    public void init() {
        pool = new StackKeyedObjectPool(factory, poolMax, poolInit);
    }


    /**
     *  Gets the stage for the id from the pool.
     *
     *@param  id                     The id
     *@return                        The stage instance
     *@exception  PipelineException  If anything goes wrong
     */
    public Stage getStage(String id)
        throws PipelineException {
        try {
            Stage c = (Stage) pool.borrowObject(id);
            return c;
        } catch (Exception ex) {
            throw new PipelineException(ex);
        }
    }



    /**
     *  Recycles the pipeline stage then returns it to the pool
     *
     *@param  o                      The pipeline stage
     *@exception  PipelineException  If anything goes wrong
     */
    public void release(Stage o)
        throws PipelineException {
        try {
            o.recycle();
            pool.returnObject(o.getId(), o);
        } catch (Exception ex) {
            throw new PipelineException(ex);
        }
    }

}

